import 'dart:convert';
import 'package:fluwx/fluwx.dart';
import 'package:tobias/tobias.dart';

class MyPayManager {
  late Fluwx fluwx = Fluwx();
  late Tobias tobias = Tobias();

  late Function(WeChatResponse) responseListener;

  void dispose() {
    fluwx.removeSubscriber(responseListener);
  }

  //检测微信是否安装
  Future<bool> checkWeChatInstalled() async {
    bool installed = await fluwx.isWeChatInstalled;
    return installed;
  }

  //检测支付宝是否安装
  Future<bool> checkAliPayInstalled() async {
    bool installed = await tobias.isAliPayInstalled;
    return installed;
  }

  // 初始化支付管理器
  void init(String appId, String universalLink) {
    // 初始化支付相关配置
    // ...

    // 初始化微信支付渠道
    fluwx.registerApi(appId: appId, universalLink: universalLink);
  }

  //去微信支付
  Future<bool> goWechatPay(Map<String, dynamic> payMap, Function(WeChatPaymentResponse) callback) async {
    await fluwx.pay(
        which: Payment(
            appId: payMap["appid"],
            partnerId: payMap["partnerid"],
            prepayId: payMap["prepayid"],
            packageValue: payMap["packageName"],
            nonceStr: payMap["noncestr"],
            timestamp: int.parse(payMap["timestamp"]),
            sign: payMap["sign"]));
    responseListener = (response) {
      if (response is WeChatPaymentResponse) {
        callback(response);
      }
    };
    fluwx.addSubscriber(responseListener);

    return true;
  }

  //去支付宝支付&回调
  Future<Map<dynamic, dynamic>> goAliPay(String order) async {
    //去支付支付
    Map<dynamic, dynamic> payReusltMap = await tobias.pay(order);
    //取消支付: {result: , memo: 支付未完成, resultStatus: 6001, platform: iOS}
    String alipayTradeAppPayResponseString = payReusltMap['result'];
    String payReuslt = "";
    if (alipayTradeAppPayResponseString.isNotEmpty) {
      Map<String, dynamic> alipayTradeAppPayResponse =
          json.decode(alipayTradeAppPayResponseString)['alipay_trade_app_pay_response'];
      if (alipayTradeAppPayResponse["code"] == "10000") {
        payReuslt = "success";
      } else {
        payReuslt = "fail";
      }
    } else {
      //取消支付
      //EasyLoading.showToast(payReusltMap["memo"]);
      payReuslt = "cancel";
    }
    return {"payReuslt": payReuslt};
  }

  //支付回调结果
  void weiChatOnRespCallback(Function(WeChatPaymentResponse) callback) {
    responseListener = (response) {
      if (response is WeChatPaymentResponse) {
        callback(response);
      }
    };
    fluwx.addSubscriber(responseListener);
  }

  // 支付功能
  void pay(String orderId, double amount) {
    // 调用支付接口
    // ...

    // 支付成功后的逻辑处理
    // ...
  }
}



/**
 * 
 * flutter: value: {result: {"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2021003143693509","auth_app_id":"2021003143693509","charset":"UTF-8","timestamp":"2024-06-06 17:42:42","out_trade_no":"SJO2024060617422700001191","total_amount":"0.01","trade_no":"2024060622001415201446346221","seller_id":"2088441210460792"},"sign":"YAOz6K/5v1F2F00cnlWLk8Z2fFskIvFOO6VZ1ogGDcPsAmbn9+YOEydRK6ZMAGNyuHIfwo5LoJztI7P03btJkdFnSedCY3GYIK9tgdg9Q3595aMkzyMS39dFbLfVYH8hiunJLVTVG2BJXL0NisB+Y+fjIPWVPJzB7U5+xnk5kO0XuFd2NDrwGkmwqeIcq2DL+KYK+chHS0a38Q6vL+dPtXW9WPrt+qRe8TNcn6smvcZM7QsxDFuDLe/TcwEf9DMM2/v8bN4nA6FeF8Na76nA7JxRvE9VkulJXtgF63GobOt3WKRfmC2z8FuuIczKDjruOwoQuQMUNXYJDrCdwdaX9Q==","sign_type":"RSA2"}, memo: , resultStatus: 9000, platform: iOS}

 * Column(
          children: [
            TextButton(
                onPressed: () {
                  myPayManager.init("wx1ee59df0d5494325", "https://mcomqa.amwaynet.com.cn/app");
                },
                child: const Text('微信注册')),
                 TextButton(
                onPressed: () {
                  myPayManager.fluwx.open(target: WeChatApp());
                },
                child: const Text('打开微信')),
            TextButton(
                onPressed: () {
                  myPayManager.goWechatPay({"appid":"wx1ee59df0d5494325","appkey":"a20facda281cb82fd639edaffe25a307","noncestr":"dca606cd8f24ae19006cb622371c5e47","outTradeNo":"1149458604817742848","packageName":"Sign=WXPay","partnerid":"1219950901","prepayid":"up_wx0422490396987247925e1ae61426bf0000","sign":"pDPD/vs9T9VjKnWfihRsqyYRTp2/at5NgQcsR1II1H669vDU+dtSeu/qNpPIfUapoyL+5G2zl+D1mcNAs9uPZQJZdxtGqoCtpfKqpTLa81dfaQr48Sttgf+lu38H+jqzYcHpReMWO6u6yrpcvyE/wJhy+Y5b3W7FZt2+9ReKItEhst1fQNCdKHU117PS30JKj6yJsMMHolgLNQfSuOFI4Trs6XZMPJCj+xrX+UDRtuxViy+GE2LS2vHGmzuILWYY4+u7wGVcwdJdEsrN3rQHYIgsK4dIbxViSJet4CB79IhvEWt2VpFwmIMGUpMLdDgS8ZP7FI8kWOyRXXC/52z61g==","timestamp":"1714834144"}, (p0) {
                    debugPrint("p0: $p0");
                  });
                },
                child: const Text('微信支付')),
            TextButton(
                onPressed: () {
                  myPayManager.goAliPay("app_id=2018032202427604&biz_content=%7B%22body%22%3A%22Amway+Product%22%2C%22out_trade_no%22%3A%22360205001062000542405040360437%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22Amway+Product%22%2C%22time_expire%22%3A%222024-05-05+00%3A16%3A59%22%2C%22timeout_express%22%3A%2290m%22%2C%22total_amount%22%3A%2261.5%22%2C%22sub_merchant%22%3A%7B%22merchant_id%22%3A%222088410895744613%22%7D%7D&charset=utf-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F10.53.84.126%3A20965%2Fsaes&sign=VVeG6NOq7dAjYr%2BfXSQQsInyKjZpnStgGPgzah2SDccAYzBqR6cG%2FEnWXQMog%2B4FOBg25VXNEJ9J7PKFTxQztHgmXhf4QdbMhJXRQ6tFCoguhOnDMgHqEmxo9JyfL6QL1SP6uot6TulkfmIjh7dcFXN3hEPuhcc%2Fv1L4UwwCrdsmZyIJxg03Rqzy20Z6XA5oRSX8%2BigtUaysqoLb%2BnzYfC9m27mYD2Rr3ikwqtXA1sJFVLnUaoWOia6Y8PndrwCH%2FKKYQdfp8%2Bhv24JqrONKP4JyITiKiDBacOtHZ48PevUWIBBJ85iMy%2Fsl9ampmVhbDDv4rFvkVDI%2B0e1muV3cYA%3D%3D&sign_type=RSA2&timestamp=2024-05-04+22%3A46%3A59&version=1.0").then((value) {
                    debugPrint("value: $value");
                  });
                },
                child: const Text('支付宝支付')),
 */